#-*- coding: utf-8 -*-
#! /usr/bin/python

import time
from PAM30 import PAMIE
import win32api
import win32con
import ConfigParser


def setRegValue(keystr, vname, value):
    '''
    设置某个注册表项的值，不存在则先添加项再设置值
    '''
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keystr, 0, win32con.KEY_ALL_ACCESS)
    try:
        kv = win32api.RegQueryValueEx(key, vname)
        if(kv==value):
            return True
        else:
            win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
            win32api.RegCloseKey(key)
    except:
        win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
        win32api.RegCloseKey(key)
        return True


def initConfig(filename):
    '''
    去掉文件头BOM等
    Window下用记事本打开配置文件并修改保存后，编码为UNICODE
    或UTF-8的文件的文件头
    #会被相应的加上\xff\xfe（\xff\xfe）或\xef\xbb\xbf
    '''
    import re
    content = open(filename).read()
    content = re.sub(r"\xfe\xff", "", content)
    content = re.sub(r"\xff\xfe", "", content)
    content = re.sub(r"\xef\xbb\xbf", "", content)
    open(filename, 'w').write(content)




def lgTaobao(username, userpass):
    '''
    使用指定用户名密码（在IE）登录淘宝
    ''' 
    #lgurl = 'http://i.taobao.com/my_taobao.htm?spm=a1z0e.3.217351.2.9fe82b&scm=1012.1.30.0'
    lgurl = 'https://login.taobao.com/member/login.jhtml?redirectURL=http%3A%2F%2Fi.taobao.com%2Fmy_taobao.htm%3Fspm%3Da1z0e.3.217351.2.9fe82b%26scm%3D1012.1.30.0'
    ie.navigate(lgurl)
    time.sleep(0.5)
    win32api.keybd_event(122, 0, 0, 0)#f11
    win32api.keybd_event(122, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(0.5)    
    ie.setTextBox('TPL_username', username.decode('utf-8'))
    time.sleep(0.3) 
    ie.setCheckBox('J_SafeLoginCheck', 0)
    time.sleep(0.2)
    bt = ie.findElement('button', 'id', 'J_SubmitStatic')
    time.sleep(0.3) 
    ie.clickElement(bt)
    #ie.setTextBox('TPL_password', userpass)
    typeme(userpass)
    time.sleep(1.5)
    ie.clickElement(bt)
    if(ie.findText(username.decode('utf-8'))):
        return True
    else:
        return False


def ordd(str):
    '''
    解决键盘码不对应问题,不知道别的电脑有没有这个问题
    '''
    t = ord(str)
    #65到90是A到Z
    if(t>90):
        return t-32
    else:
        return t


def typeme(passw):
    '''
    模拟人工输入,自动输入参数字符串到焦点窗口
    '''
    psht = len(passw)
    for j in range(psht):
        win32api.keybd_event(ordd(passw[j]), 0, 0, 0)
        time.sleep(0.5)
        win32api.keybd_event(ordd(passw[j]), 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(0.5)


def pai(ppass, count):
        #设置数量
        #counttext = ie.findElement('input','id','J_IptAmount')
        ie.setTextBox('J_IptAmount', count)
        #拍下
        time.sleep(1.5)
        buy = ie.findElement('div', 'id', 'J_juValid')
        a = ie.getElementChildren(buy)
        b = ie.getElementChildren(a[0])
        eleArry = ie.getElementChildren(buy)
        ie.clickElement(b[0])
        time.sleep(2)
        #购买
        go = ie.findElement('a', 'id', 'J_Go')
        ie.clickElement(go)
        time.sleep(3)
        #到支付页面
        pp = ie.findElement('input', 'id', 'payPassword')
        ie.clickHiddenElement(pp)
        pay = ie.findElement('input', 'id', 'J_authSubmit')
        ie.clickElement(pay)
        time.sleep(1)
        #输入密码
        typeme(ppass)
        ie.clickElement(pay)
        time.sleep(2)

#读取配置文件
keystr = 'SOFTWARE\\Microsoft\\Internet Explorer\\New Windows\\Allow'
setRegValue(keystr, 's.taobao.com', '0')
config = ConfigParser.ConfigParser()
initConfig('base.ini')
config.read('base.ini')
username = config.get("global", "taobaoid")
userpass = config.get("global", "loginpass")
ppass = list(config.get("global", "paypass"))
mtaoid = config.get("global", "mtaoid")

ie= PAMIE()
lgTaobao(username, userpass)
time.sleep(1.2)
itemcount = int(config.get("global", "itemcount"))
count = config.getint("global", "count")
itemlist = range(itemcount)
for i in range(itemcount):
    itemlist[i] = config.get("items", "item"+str(i+1))    
    ie.navigate(itemlist[i])
    time.sleep(1.5)           
    pai(ppass, str(count))

